package pro.softzhang.algo.lc500;

public class LC567_PermutationInString {
    public static void main(String[] args) {
        String s1 = "a", s2 = "ab";
        boolean in = new LC567_Solution1().checkInclusion(s1, s2);
        System.out.println(in);
    }
}

class LC567_Solution {
    public boolean checkInclusion(String s1, String s2) {
        if(s1.length() > s2.length()) {
            return false;
        }

        int[] counts = new int[26];
        for (int i = 0; i < s1.length(); i++) {
            counts[s1.charAt(i) - 'a']++;
            counts[s2.charAt(i) - 'a']--;
        }

        if(areAllZero(counts)) {
            return true;
        }

        for (int i = s1.length(); i < s2.length(); i++) {
            counts[s2.charAt(i) - 'a']--;
            counts[s2.charAt(i - s1.length()) - 'a']++;
            if(areAllZero(counts)) {
                return true;
            }
        }

        return false;
    }

    private boolean areAllZero(int[] counts) {
        for (int count : counts) {
            if(count != 0) {
                return false;
            }
        }
        return true;
    }
}

class LC567_Solution1 {
    public boolean checkInclusion(String s1, String s2) {
        if(s1.length() > s2.length()) {
            return false;
        }

        int[] counts = new int[26];

        for (int i = 0; i < s1.length(); i++) {
            counts[s1.charAt(i) - 'a']++;
            counts[s2.charAt(i) - 'a']--;
        }

        if(areAllZero(counts)) {
            return true;
        }

        int p1 = s1.length(), p2 = p1 - s1.length();
        while (p1 < s2.length()) {
            counts[s2.charAt(p1) - 'a']--;
            counts[s2.charAt(p2) - 'a']++;
            if(areAllZero(counts)) {
                return true;
            }
            p1++;
            p2++;
        }
        return false;
    }

    private boolean areAllZero(int[] counts) {
        for (int count : counts) {
            if(count != 0) {
                return false;
            }
        }
        return true;
    }
}